const querySql = require("./sql");
const express = require("express");
const cors = require("cors");
const app = express();
const port = 8888;
// 启用 CORS 中间件
app.use(cors());
app.use(express.json());
app.use(cors({
  origin: 'http://localhost:3000', // 允许访问的域名
  methods: 'GET,POST,PUT,DELETE', // 允许的方法
  allowedHeaders: 'Content-Type,x-requested-with', // 允许的头信息
  credentials: true, // 允许携带凭证信息
}));


// 定义addSql函数，并接收res作为参数
let addSql = async (query, res) => {
  const { id, title, noticeContent } = query;
  let add = "INSERT INTO rich_text (id, title, noticeContent) VALUES (?, ?, ?)";
  let values = [id, title, noticeContent];
  try {
    const result = await querySql(add, values);
    if (result.affectedRows == 1) {
      console.log("添加成功");
      // 发送查询结果
      res.status(200).json({
        code: 200,
        data: {
          code: 200
        },
        message: "添加成功！"
      });
    }
  } catch (err) {
    console.error(err);
    res.status(500).json({ // 发送错误响应
      code: 500,
      message: err
    });
  }
};

app.post("/add", (req, res) => {
  console.log(req)
  let rules = true;
  if (rules) {
    addSql(req.query, res);
  } else {
    res.status(400).json({
      code: 400,
      message: "请求参数验证失败"
    });
  }
});

app.post("/page", async (req, res) => {
  console.log(req.query);
  var { page = 1, pageSize = 10 } = req.query;
  page = parseInt(page)
  pageSize = parseInt(pageSize)
  // const pageSizeList = [10, 20, 50];

  // if (!pageSizeList.includes(parseInt(pageSize))) {
  //   return res.status(400).json({ // 发送pageSize错误的响应
  //     code: 400,
  //     message: 'pageSize参数错误'
  //   });
  // }

  try {
    const data = await pageQuery(page, pageSize);
    res.status(200).json({
      code: 200,
      data: data,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      data: data,
      total: data.length - 1
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '查询失败'
    });
  }
});

const pageQuery = async (page, pageSize) => {
  let offset = (page - 1) * pageSize;
  let select = "SELECT * FROM rich_text LIMIT ? OFFSET ?";
  let values = [pageSize, offset];
  try {
    const result = await querySql(select, values);
    return result; // 返回查询结果
  } catch (err) {
    console.error(err);
    throw err; // 抛出错误以供调用者处理
  }
};

app.listen(port, () => {
  console.log(`服务器已经启动，监听端口 ${port}`);
});